#include "recv.h"

unsigned char cData[] = "hello world test";

void PublishSuccess(int publishId)
{
	printf("[PublishSuccess]CB: publish %d done\n", publishId);
}

void PublishFailed(int publishId, PublishFailReason reason)
{
	printf("[PublishFailed]CB: publish %d failed, reason=%d\n", publishId, (int)reason);
}

int PublishServiceInterface(int publish_id)
{
	PublishInfo info = {
		.publishId = publish_id,
		.mode = DISCOVER_MODE_PASSIVE,
		.medium = COAP,
		.freq = LOW,
		.capability = "osdCapability",
		.capabilityData = cData,
		.dataLen = sizeof(cData),
	};
	IPublishCallback cb = {
		.OnPublishSuccess = PublishSuccess,
		.OnPublishFail = PublishFailed,
	};

	// PublishService(pkgName, &info, &cb);
	// info.publishId = g_publishID + 1;
	// info.mode = DISCOVER_MODE_ACTIVE;

	return PublishService(pkgName, &info, &cb);
}

int SessionOpened(int sessionId, int result)
{
	printf("[SessionOpened]CB: session %d open ret=%d\n", sessionId, result);
	return 0;
}

void SessionClosed(int sessionId)
{
	printf("[SessionClosed]CB: session %d closed\n", sessionId);
}

void ByteRecived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("[ByteRecived]CB: session %d received %u\n", sessionId, dataLen);
	FILE *fb = fopen("./out.yuv", "ab+");
	fwrite(data, 1, dataLen, fb);
	fclose(fb);
}

void MessageReceived(int sessionId, const void *data, unsigned int dataLen)
{
	printf("[MessageReceived]CB: session %d received %u bytes message=%s\n", sessionId, dataLen, (const char *)data);
}

const ISessionListener sessionCB = {
	.OnSessionOpened = SessionOpened,
	.OnSessionClosed = SessionClosed,
	.OnBytesReceived = ByteRecived,
	.OnMessageReceived = MessageReceived,
};

int main(int argc, char **argv)
{
	bool needContinue = true;
	int ret;

	ret = PublishServiceInterface(g_publishID);
	if (ret) {
		printf("PublishService fail, ret=%d\n", ret);
		goto err_PublishService;
	}
	ret = CreateSessionServer(pkgName, sessionName, &sessionCB);
	if (ret) {
		printf("CreateSessionServer fail, ret=%d\n", ret);
		goto err_CreateSessionServer;
	}
	while (needContinue) {
		printf("Input s to stop:\n");
		char op = getchar();
		switch(op) {
		case 's':
		case 'S':
			needContinue = false;
			break;
		default:
			break;
		}
	}
	RemoveSessionServer(pkgName, sessionName);
err_CreateSessionServer:
	UnPublishService(pkgName, g_publishID);
err_PublishService:
	return 0;
}

